package net.doyouhike.app.bbs.ui.widget.action;

import android.animation.LayoutTransition;
import android.animation.LayoutTransition.TransitionListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import net.doyouhike.app.bbs.R;
import net.doyouhike.app.bbs.util.BitmapUtil;
import net.doyouhike.app.bbs.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 这是一个富文本编辑器，给外部提供insertImage接口，添加的图片跟当前光标所在位置有关
 */
@SuppressLint({"NewApi", "InflateParams"})
public class RichTextEditor extends ScrollView {

    private int viewTagIndex = 1; // 新生的view都会打一个tag，对每个view来说，这个tag是唯一的。
    private LinearLayout allLayout; // 这个是所有子view的容器，scrollView内部的唯一一个ViewGroup
    private LayoutInflater inflater;
    private OnKeyListener keyListener; // 所有EditText的软键盘监听器
    private OnClickListener btnListener; // 图片右上角红叉按钮监听器
    private OnFocusChangeListener focusListener; // 所有EditText的焦点监听listener
    private EditText lastFocusEdit; // 最近被聚焦的EditText
    private LayoutTransition mTransitioner; // 只在图片View添加或remove时，触发transition动画
    private int disappearingImageIndex = 0;

    EditText firstEdit;

    /**
     * 编辑数据
     */
    private EditData mEditData;

    /**
     * 删除的图片
     */
    private ArrayList<String> delImages = new ArrayList<>();

    public RichTextEditor(Context context) {
        this(context, null);
    }

    public RichTextEditor(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RichTextEditor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        inflater = LayoutInflater.from(context);

        // 1. 初始化allLayout
        allLayout = new LinearLayout(context);
        allLayout.setOrientation(LinearLayout.VERTICAL);
        allLayout.setBackgroundColor(Color.WHITE);
        setupLayoutTransitions();
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        addView(allLayout, layoutParams);

        // 2. 初始化键盘退格监听
        // 主要用来处理点击回删按钮时，view的一些列合并操作
        keyListener = new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && event.getKeyCode() == KeyEvent.KEYCODE_DEL) {
                    EditText edit = (EditText) v;
                    onBackspacePress(edit);
                }
                return false;
            }
        };

        // 3. 图片叉掉处理
        btnListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                RelativeLayout parentView = (RelativeLayout) v.getParent();
                onImageCloseClick(parentView);
                //合并textview
                mergeEditText();

            }
        };

        focusListener = new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    lastFocusEdit = (EditText) v;
                    if (StringUtil.isNotEmpty(lastFocusEdit.getHint().toString()))
                        lastFocusEdit.setHint("");
                    showKeyBoard();

                }
            }
        };

        createFirstEidt();
    }

    private void createFirstEidt() {
        LinearLayout.LayoutParams firstEditParam = new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        firstEdit = createEditText(getContext().getString(R.string.edit_event_tint));
        allLayout.addView(firstEdit, firstEditParam);
        lastFocusEdit = firstEdit;

    }

    /**
     * 处理软键盘backSpace回退事件
     *
     * @param editTxt 光标所在的文本输入框
     */
    private void onBackspacePress(EditText editTxt) {
        int startSelection = editTxt.getSelectionStart();
        // 只有在光标已经顶到文本输入框的最前方，在判定是否删除之前的图片，或两个View合并
        if (startSelection == 0) {
            int editIndex = allLayout.indexOfChild(editTxt);
            View preView = allLayout.getChildAt(editIndex - 1); // 如果editIndex-1<0,
            // 则返回的是null
            if (null != preView) {
                if (preView instanceof RelativeLayout) {
                    // 光标EditText的上一个view对应的是图片
                    onImageCloseClick(preView);
                } else if (preView instanceof EditText) {
                    // 光标EditText的上一个view对应的还是文本框EditText
                    String str1 = editTxt.getText().toString();
                    EditText preEdit = (EditText) preView;
                    String str2 = preEdit.getText().toString();

                    // 合并文本view时，不需要transition动画
                    allLayout.setLayoutTransition(null);
                    allLayout.removeView(editTxt);
                    allLayout.setLayoutTransition(mTransitioner); // 恢复transition动画

                    // 文本合并
                    preEdit.setText(str2 + str1);
                    preEdit.requestFocus();
                    preEdit.setSelection(str2.length(), str2.length());
                    lastFocusEdit = preEdit;
                }
            }
        }
    }

    /**
     * 处理图片叉掉的点击事件
     *
     * @param view 整个image对应的relativeLayout view
     * @type 删除类型 0代表backspace删除 1代表按红叉按钮删除
     */
    private void onImageCloseClick(View view) {
        if (!mTransitioner.isRunning()) {
            disappearingImageIndex = allLayout.indexOfChild(view);
            allLayout.removeView(view);
        }
    }

    /**
     * 生成文本输入框
     */
    private EditText createEditText(String hint) {
        EditText editText = (EditText) inflater.inflate(R.layout.widget_action_detail_more_edit_item,
                null);
        editText.setOnKeyListener(keyListener);
        editText.setTag(viewTagIndex++);
        editText.setHint(hint);
        editText.setOnFocusChangeListener(focusListener);
        editText.setLineSpacing(10f, 1f);
        editText.setTextColor(getContext().getResources().getColor(R.color.txt_title_light_standard));
        return editText;
    }

    /**
     * 生成图片View
     */
    private RelativeLayout createImageLayout() {
        RelativeLayout layout = (RelativeLayout) inflater.inflate(
                R.layout.widget_action_detail_more_edit_imageview, null);
        layout.setTag(viewTagIndex++);
        View closeView = layout.findViewById(R.id.image_close);
        closeView.setTag(layout.getTag());
        closeView.setOnClickListener(btnListener);
        return layout;
    }


    /**
     * 根据绝对路径添加view
     *
     * @param imagePath
     */
    public void insertImage2(String imagePath) {
        //判断是否是网络图片
        addImageViewAtIndex(imagePath);


    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        lastFocusEdit.callOnClick();
        lastFocusEdit.requestFocus();
        return super.onTouchEvent(ev);
    }


    /**
     * 插入模板文本
     *
     * @param
     */
    public void insertTemplateContent(String attention, String disclaimer) {
        StringBuffer stringBuffer = new StringBuffer(lastFocusEdit.getText());

        if (!TextUtils.isEmpty(attention)) {

            if (!TextUtils.isEmpty(stringBuffer)) {
                stringBuffer.append("\n");
            }
            addEditText("\n注意事项\n");
            String[] attentions = attention.split("\n");
            for (int i = 0; i < attentions.length; i++) {
                addEditText(attentions[i]);
            }

        }

        if (!TextUtils.isEmpty(disclaimer)) {

            if (!TextUtils.isEmpty(stringBuffer)) {
                stringBuffer.append("\n");
            }
            addEditText("\n免责声明\n");
            String[] disclaimers = disclaimer.split("\n");
            for (int j = 0; j < disclaimers.length; j++) {
                addEditText(disclaimers[j]);
            }
        }
        addEditText("");

    }

    /**
     * 插入一张图片
     */
    private void insertImage(Bitmap bitmap, String imagePath) {
        String lastEditStr = lastFocusEdit.getText().toString();
        int cursorIndex = lastFocusEdit.getSelectionStart();
        String editStr1 = lastEditStr.substring(0, cursorIndex).trim();
        int lastEditIndex = allLayout.indexOfChild(lastFocusEdit);

        if (lastEditStr.length() == 0 || editStr1.length() == 0) {
            // 如果EditText为空，或者光标已经顶在了editText的最前面，则直接插入图片，并且EditText下移即可
            addImageViewAtIndex(lastEditIndex, bitmap, imagePath);
        } else {
            // 如果EditText非空且光标不在最顶端，则需要添加新的imageView和EditText
            lastFocusEdit.setText(editStr1);
            String editStr2 = lastEditStr.substring(cursorIndex).trim();
            if (allLayout.getChildCount() - 1 == lastEditIndex
                    || editStr2.length() > 0) {
                addEditTextAtIndex(lastEditIndex + 1, editStr2);
            }

            addImageViewAtIndex(lastEditIndex + 1, bitmap, imagePath);
            lastFocusEdit.requestFocus();
            lastFocusEdit.setSelection(editStr1.length(), editStr1.length());
        }
        hideKeyBoard();
    }

    /**
     * 隐藏小键盘
     */
    public void hideKeyBoard() {
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(lastFocusEdit.getWindowToken(), 0);
    }

    /**
     * 隐藏小键盘
     */
    public void showKeyBoard() {
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(lastFocusEdit, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 在特定位置插入EditText
     *
     * @param index   位置
     * @param editStr EditText显示的文字
     */
    private void addEditTextAtIndex(final int index, String editStr) {
        firstEdit.setHint("");
        EditText editText2 = createEditText("");
        editText2.setText(editStr);

        // 请注意此处，EditText添加、或删除不触动Transition动画
        allLayout.setLayoutTransition(null);
        allLayout.addView(editText2, index);
        allLayout.setLayoutTransition(mTransitioner); // remove之后恢复transition动画
    }

    /**
     * 在特定位置插入EditText
     * 位置
     *
     * @param editStr EditText显示的文字
     */
    private void addEditText(String editStr) {
        firstEdit.setHint("");
        EditText editText2 = createEditText("");
        editText2.setText(editStr);

        // 请注意此处，EditText添加删除不触动Transition动画
        allLayout.setLayoutTransition(null);
        allLayout.addView(editText2);
        allLayout.setLayoutTransition(mTransitioner); // remove之后恢复transition动画
    }

    /**
     * dp和pixel转换
     *
     * @param dipValue dp值
     * @return 像素值
     */
    public int dip2px(float dipValue) {
        float m = getContext().getResources().getDisplayMetrics().density;
        return (int) (dipValue * m + 0.5f);
    }

    /**
     * 在特定位置添加ImageView
     */
    private void addImageViewAtIndex(final int index, Bitmap bmp,
                                     String imagePath) {
        final RelativeLayout imageLayout = createImageLayout();
        DataImageView imageView = (DataImageView) imageLayout
                .findViewById(R.id.edit_imageView);
        imageView.setImageBitmap(bmp);
        imageView.setBitmap(bmp);
        imageView.setAbsolutePath(imagePath);

        // 调整imageView的高度 等比例缩放
        int imageHeight = bmp.getWidth();
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, imageHeight);
        imageView.setLayoutParams(lp);
        lp.setMargins(0, dip2px(10), 0, dip2px(10));
        // onActivityResult无法触发动画，此处post处理
        allLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                allLayout.addView(imageLayout);
            }
        }, 200);
    }

    /**
     * 在特定位置添加ImageView
     */
    public void addLocalImage(String imagePath) {
        Bitmap bmp = BitmapFactory.decodeFile(imagePath);
        final RelativeLayout imageLayout = createImageLayout();
        DataImageView imageView = (DataImageView) imageLayout
                .findViewById(R.id.edit_imageView);
        imageView.setImageBitmap(bmp);
        imageView.setBitmap(bmp);
        imageView.setAbsolutePath(imagePath);

        // 调整imageView的高度 等比例缩放
        int imageHeight = getWidth() * bmp.getHeight() / bmp.getWidth();

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, imageHeight);
        imageView.setLayoutParams(lp);

        int lastEditIndex = allLayout.indexOfChild(lastFocusEdit);
        allLayout.setLayoutTransition(null);
        allLayout.addView(imageLayout, lastEditIndex + 1);
        allLayout.setLayoutTransition(mTransitioner);
        addEditTextAtIndex(lastEditIndex + 2, "");
    }

    /**
     * 在特定位置添加ImageView
     */
    private void addImageViewAtIndex(
            final String imagePath) {
        final RelativeLayout imageLayout = createImageLayout();
        final DataImageView imageView = (DataImageView) imageLayout
                .findViewById(R.id.edit_imageView);

        Glide.with(getContext())
                .load(imagePath)
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.color.default_image_background)
                .fitCenter()
                .into(new SimpleTarget<Bitmap>() {

                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        if (imageLayout != null && imageView != null && resource != null) {
                            imageView.setImageBitmap(resource);
                            imageView.setBitmap(resource);
                            imageView.setAbsolutePath(imagePath);

                            // 调整imageView的高度 等比例缩放
                            int imageHeight = getWidth() * resource.getHeight() / resource.getWidth();

                            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                                    LayoutParams.MATCH_PARENT, imageHeight);
                            imageView.setLayoutParams(lp);
                            allLayout.setLayoutTransition(null);
                            allLayout.requestLayout();

                        }
                    }
                });


        int lastEditIndex = allLayout.indexOfChild(lastFocusEdit);
        allLayout.addView(imageLayout, lastEditIndex);

//        View closeView = imageLayout.findViewById(R.id.image_close);
//        closeView.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                RelativeLayout parentView = (RelativeLayout) v.getParent();
//                onImageCloseClick(parentView);
//                //合并textview
//                mergeEditText();
//                EditData.ImgText temp = getContainImage(imagePath);
//                if (temp != null) {
//                    delImages.add(temp.getPhotoId());
//                }
//
//            }
//        });

    }

    /**
     * 根据view的宽度，动态缩放bitmap尺寸
     *
     * @param width view的宽度
     */
    private Bitmap getScaledBitmap(String filePath, int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int sampleSize = options.outWidth > width ? options.outWidth / width
                + 1 : 1;
        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;
        return BitmapUtil.decodeFile(filePath);
    }

    /**
     * 初始化transition动画
     */
    private void setupLayoutTransitions() {
        mTransitioner = new LayoutTransition();
        allLayout.setLayoutTransition(mTransitioner);
        mTransitioner.addTransitionListener(new TransitionListener() {

            @Override
            public void startTransition(LayoutTransition transition,
                                        ViewGroup container, View view, int transitionType) {

            }

            @Override
            public void endTransition(LayoutTransition transition,
                                      ViewGroup container, View view, int transitionType) {
                if (!transition.isRunning()
                        && transitionType == LayoutTransition.CHANGE_DISAPPEARING) {
                    // transition动画结束，合并EditText
                    // mergeEditText();
                }
            }
        });
        mTransitioner.setDuration(300);
    }

    /**
     * 图片删除的时候，如果上下方都是EditText，则合并处理
     */
    private void mergeEditText() {
        //防止下标越界
        if (disappearingImageIndex > 0) {
            View preView = allLayout.getChildAt(disappearingImageIndex - 1);
            View nextView = allLayout.getChildAt(disappearingImageIndex);
            if (preView != null && preView instanceof EditText && null != nextView
                    && nextView instanceof EditText) {
                Log.d("LeiTest", "合并EditText");
                EditText preEdit = (EditText) preView;
                EditText nextEdit = (EditText) nextView;
                String str1 = preEdit.getText().toString();
                String str2 = nextEdit.getText().toString();
                String mergeText = "";
                if (str2.length() > 0) {
                    mergeText = str1 + "\n" + str2;
                } else {
                    mergeText = str1;
                }

                allLayout.setLayoutTransition(null);
                allLayout.removeView(nextEdit);
                preEdit.setText(mergeText);
                preEdit.requestFocus();
                preEdit.setSelection(str1.length(), str1.length());
                allLayout.setLayoutTransition(mTransitioner);
            }
        }

    }


    /**
     * 对外提供的接口, 生成编辑数据上传
     */
    public EditData buildEditData() {
        EditData editData = new EditData();

        ArrayList<EditData.ImgText> dataList = new ArrayList<>();
        int num = allLayout.getChildCount();
        for (int index = 0; index < num; index++) {
            View itemView = allLayout.getChildAt(index);
            EditData.ImgText itemData = new EditData.ImgText();

            if (itemView instanceof EditText) {
                EditText item = (EditText) itemView;
                String text = item.getText().toString();
                itemData.setInputStr(text);


            } else if (itemView instanceof RelativeLayout) {
                DataImageView item = (DataImageView) itemView
                        .findViewById(R.id.edit_imageView);

                itemData.setImagePath(item.getAbsolutePath());
                EditData.ImgText temp = getContainImage(item.getAbsolutePath());
                if (temp != null && StringUtil.isNotEmpty(temp.getPhotoId())) {
                    itemData.setIsNew("0");
                    itemData.setPhotoId(temp.getPhotoId());
                } else {
                    itemData.setIsNew("1");
                    itemData.setPhotoId("");
                }

            }
            dataList.add(itemData);
        }
        if (dataList.get(0).getImagePath() == null
                && dataList.get(0).getInputStr() != null
                && dataList.get(0).getInputStr().length() <= 0)
            dataList.remove(0);
        editData.setImgTexts(dataList);
        editData.setDel_photoId(delImages);
        return editData;
    }

    public EditData.ImgText getContainImage(String imgPath) {
        if (mEditData.getImgTexts() == null)
            return null;
        List<EditData.ImgText> items = mEditData.getImgTexts();
        if (items == null || items.isEmpty())
            return null;
        for (EditData.ImgText item : items) {
            if (StringUtil.isNotEmpty(imgPath) && imgPath.equals(item.getImagePath())) {
                return item;
            }
        }
        return null;
    }


    /**
     * 初始化 data
     * <p/>
     * list
     */

    public void initData(EditData source) {
        mEditData = source;
        //删除的历史记录
        if (mEditData.getDel_photoId() != null) {
            delImages = mEditData.getDel_photoId();
        }

        if (null != source.getImgTexts() && source.getImgTexts().size() > 0) {
            int size = source.getImgTexts().size();
            allLayout.removeAllViews();
            for (int i = 0; i < size; i++) {
                if (StringUtil.isNotEmpty(source.getImgTexts().get(i).getImagePath())) {
                    insertImage2(source.getImgTexts().get(i).getImagePath());
                } else if (source.getImgTexts().get(i).getInputStr() != null) {
                    addEditText(source.getImgTexts().get(i).getInputStr());
                }

            }
        }
    }


}
